package managers
{
	import com.leebrimelow.starling.StarlingPool;
	
	import core.Assets;
	import core.Game;
	
	import objects.Explosion;
	
	import starling.core.Starling;
	import starling.events.Event;
	
	import states.Play;

	public class ExplosionManager
	{
		private var _play:Play;
		private var _pool:StarlingPool;
		
		public function ExplosionManager(play:Play)
		{
			this._play = play;
			
			_pool = new StarlingPool(Explosion, 15);;
		}
		
		public function spawn(x:int, y:int):void
		{
			Game.SOUND_MANAGER.item(Assets.PLAY_ENEMY_EXPLODE).play();
			
			var ex:Explosion = _pool.getSprite() as Explosion;
			_play.addChild(ex);
			ex.alignPivot("center", "center");
			ex.scaleX = ex.scaleY = 0.35;
			ex.x = x;
			ex.y = y;
			ex.start(.25);
			Starling.juggler.add(ex);
			ex.addEventListener(Event.COMPLETE, onComplete);
		}
		
		public function destroy():void
		{
			for (var i:int = 0; i < _pool.items.length; i++)
			{
				var ex:Explosion = _pool.items[i] as Explosion;
				if (ex.hasEventListener(Event.COMPLETE))
				{
					ex.removeEventListeners(Event.COMPLETE);
				}
				Starling.juggler.remove(ex);
				_play.removeChild(ex);
				ex.dispose();
				ex = null;
			}
			
			_pool.destroy();
			_play = null;
		}
		
		private function onComplete(e:Event):void
		{
			var ex:Explosion = e.currentTarget as Explosion;
			ex.removeEventListener(Event.COMPLETE, onComplete);
			
			if (_pool != null)
			{
				_pool.returnSprite(ex);
			}
			
			Starling.juggler.remove(ex);
			_play.removeChild(ex);
		}
	}
}



































